package org.lk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.lk.reggie.common.R;
import org.lk.reggie.entity.Category;
import org.lk.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController
{
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> addCategory(@RequestBody Category category)
    {
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> getAll(@RequestParam Integer pageSize, @RequestParam("page") Integer currentPage)
    {
        // 构造分页器
        Page pageInfo = new Page(currentPage, pageSize);

        // 添加构造条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();

        // 添加排序条件
        queryWrapper.orderByDesc(Category :: getSort);

        // 执行查询
        categoryService.page(pageInfo);

        return R.success(pageInfo);
    }


    @DeleteMapping()
    public R<String> deleteCate(@RequestParam("id") Long id)
    {
//        boolean b = categoryService.removeById(id);

        boolean b = categoryService.myRemoveById(id);
        if (b)
            return R.success("删除成功");
        return R.error("删除失败");
    }


    @PutMapping
    public R<String> updateCategory(@RequestBody Category category)
    {
        boolean b = categoryService.updateById(category);
        if (b)
            return R.success("修改成功");
        return R.error("修改失败");
    }


    @GetMapping("/list")
    public R<List<Category>> getCategoryList(Category category)
    {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(category.getType() != null, Category :: getType, category.getType());
        queryWrapper.orderByDesc(Category :: getSort).orderByDesc(Category:: getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);
        if (list.size() > 0)
            return R.success(list);
        return R.error("error");
    }
}
